import { request } from '../../request/index'
import regeneratorRuntime from "../../lib/runtime/runtime"
Page({
  data: {
    cart: [],
    address: {},
    totalNum: 0,
    totalPrice: 0
  },
  /*监听页面加载*/
  onLoad: function (options) {
  },
  onShow: function() {
    const address = wx.getStorageSync('address');
    let cart = wx.getStorageSync('cart') || [];
    cart = cart.filter(v => v.checked);
    let totalNum = 0;
    let totalPrice = 0;
    cart.forEach(v => {
      totalPrice += v.num * v.goods_price;
      totalNum += v.num;
    })
    this.setData({ cart, totalNum, totalPrice, address });
  },
  // 支付
  async orderPay() {
    // 1. 获取token
    const token = wx.getStorageSync('token')
    if(!token) {
      wx.navigateTo({ url: '/pages/auth/auth' });
      return;
    }
    // 2. 创建订单
    const header = { Authorization: token }
    const order_price = this.data.totalPrice;
    const consignee_addr = this.data.address.all;
    const cart = this.data.cart;
    let goods = [];
    cart.forEach(v => {
      goods.push({
        goods_number: v.num,
        goods_id: v.goods_id,
        goods_price: v.goods_price
      })
    })
    const params = { order_price, consignee_addr, goods }
    const res = await request({
      header,
      method: 'post',
      data: params,
      url: 'my/orders/create'
    })
    console.log(res, 'res');
  }
})
